# Create your views here.

import itertools
import operator
from pprint import pprint

from django.shortcuts import render_to_response
from django.template import RequestContext

# Don't seem to need these anymore...
#from django.template import Context, loader
#from django.http import HttpResponse

# import the Django project settings
from naimath_project import settings

from naimath.engine import engine, question

Debug = True

Rule_base = 'pulmonary'

def load_translations(request, *domains):
    #languages = request.accept_language.best_matches()
    languages = (request.LANGUAGE_CODE, 'en_US', 'en_IN')
    if Debug:
        print "request", request
        print "dir(request)", dir(request)
        print "request.LANGUAGE_CODE", request.LANGUAGE_CODE
        print "settings.LOCALE_DIR", settings.LOCALE_DIR
        #print "request.accept_language.best_matches()", \
        #      request.accept_language.best_matches()
    question.load_translations(settings.LOCALE_DIR, languages, *domains)

def consult(rule_base, symptom={}, sign={}, investigation={}):
    r'''Consult the naimath engine.

    Returns two lists:
        * a list of (diagnosis, cf, [(question, relevance_score)]) sorted by
          descending cf and relevance_score.
        * a list of (question, combined_relevance_score) sorted by descending
          combined_relevance_score.
    '''
    return engine.consult(rule_base, symptom=symptom, sign=sign,
                          investigation=investigation)

def step1(request):
    return render_to_response('naimath_app/step1.html', {},
                              context_instance=RequestContext(request))

def step2(request):
    return render_to_response('naimath_app/step2.html', {},
                              context_instance=RequestContext(request))

def step3(request):
    load_translations(request, 'diagnosis',
                               'symptom',
                             # 'sign',
                               'investigation')
    answers = request.POST
    if Debug:
        pprint(("answers", answers))
        for cat, qs in itertools.groupby((tuple(key.split(':')) + (values,)
                                          for key, values
                                           in sorted(answers.iteritems())
                                           if key != u'csrfmiddlewaretoken'),
                                         key=operator.itemgetter(0)):
            pprint((cat, tuple(qs)))
    facts = dict(
              (category, dict((q_name, answer)
                              for _, q_name, answer in questions))
              for category, questions
               in itertools.groupby((tuple(key.split(':')) + (values,)
                                     for key, values
                                      in sorted(answers.iteritems())
                                      if key != u'csrfmiddlewaretoken'),
                                    key=operator.itemgetter(0)))
    if Debug:
        pprint(("facts", facts))
    diagnosis, questions = consult(Rule_base, **facts) 
    if Debug:
        pprint(("diagnosis", diagnosis))
        pprint(("questions", questions))
    return render_to_response('naimath_app/step3.html',
                              {'answers': answers,
                               'diagnosis': diagnosis,
                               'questions': [
                                 (':'.join((category, q_name)), relevance)
                                 for category, q_name, relevance in questions],
                              },
                              context_instance=RequestContext(request))

def step4(request):
    return render_to_response('naimath_app/step4.html', {},
                              context_instance=RequestContext(request))

def step5(request):
    return render_to_response('naimath_app/step5.html', {},
                              context_instance=RequestContext(request))

